<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-alert center title="添加商品信息" type="info" show-icon> </el-alert>
      <!-- 步骤条 -->
      <el-steps
        align-center
        :space="200"
        :active="activeName - 0"
        finish-status="success"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tabs标签 -->
      <el-form
        :model="addGoodsForm"
        :rules="addGoodsFormRules"
        ref="addGoodsFormRef"
        class="demo-ruleForm"
        label-position:top
      >
        <el-tabs
          v-model="activeName"
          :tab-position="'left'"
          :before-leave="beforeLeave"
        >
          <!-- 基本信息页 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGoodsForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addGoodsForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addGoodsForm.goods_number"></el-input>
            </el-form-item>
            <!-- 级联选择器 -->
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addGoodsForm.goods_cat"
                :options="options"
                :props="props"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数信息 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              v-for="item in goodsManyParams"
              :key="item.attr_id"
              :label="item.attr_name"
              ><br />
              <el-checkbox-group v-model="checkList" @change="checkchange">
                <el-checkbox
                  border
                  v-for="(item1, index) in item.attr_vals"
                  :key="index"
                  :label="item1"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in goodsOnlyParams"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 图片上传 -->
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="uploadSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addGoodsForm.goods_introduce" />
            <el-button @click="addGoods" class="btnAdd" type="primary"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 预览图片的弹出框 -->
    <el-dialog title="预览图片" :visible.sync="dialogVisible" width="40%">
      <img class="image" :src="lookUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import _ from "lodash";
export default {
  data() {
    return {
      // 被激活的哪一个
      activeName: "0",
      // 表单绑定的数据
      addGoodsForm: {
        goods_name: "",
        goods_price: 1,
        goods_number: 1,
        goods_weight: 1,
        goods_cat: [],
        pics: [],
        goods_introduce: "",
        attrs: [],
      },
      // 表单的验证规则
      addGoodsFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
      },
      // 级联选择器绑定的值
      options: [],
      props: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      // 商品动态参数数据
      goodsManyParams: [],
      checkList: [],
      // 商品的静态参数列表
      goodsOnlyParams: [],
      // 上传图片的url地址
      uploadUrl: "http://127.0.0.1:8888/api/private/v1/upload",
      headerObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      // 预览图片的路径
      lookUrl: "",
      // 控制预览图片的对话框
      dialogVisible: false,
    };
  },
  methods: {
    // 级联选择器的值发生变化时
    handleChange(val) {
      // console.log(val);
      if (this.addGoodsForm.goods_cat.length !== 3) {
        this.addGoodsForm.goods_cat = [];
      } else {
        console.log(this.addGoodsForm.goods_cat);
      }
    },
    // 获取分类的所有列表
    async getGoodsList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品列表失败");
      } else {
        this.options = res.data;
        console.log(this.options);
      }
    },
    // tab栏切换之前进行的操作
    beforeLeave(activeName, oldActiveName) {
      if (oldActiveName === "0" && this.addGoodsForm.goods_cat.length === 0) {
        this.$message.error("请先选择分类");
        return false;
      } else if (activeName === "1") {
        this.getGoodsMany();
      } else if (activeName === "2") {
        this.getGoodsOnly();
      }
    },
    // 获取商品的动态参数
    async getGoodsMany() {
      const { data: res } = await this.$http.get(
        "categories/" + this.addGoodsForm.goods_cat[2] + "/attributes",
        { params: { sel: "many" } }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("获取动态参数失败");
      }
      this.goodsManyParams = res.data;
      this.goodsManyParams.forEach((item) => {
        item.attr_vals =
          item.attr_vals.length !== 0 ? item.attr_vals.split(" ") : [];
      });
      // console.log(this.goodsManyParams);
    },
    // 获取商品的静态属性
    async getGoodsOnly() {
      const { data: res } = await this.$http.get(
        "categories/" + this.addGoodsForm.goods_cat[2] + "/attributes",
        { params: { sel: "only" } }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("获取静态属性列表失败");
      }
      this.goodsOnlyParams = res.data;
      console.log(this.goodsOnlyParams);
      // this.goodsManyParams.forEach(item=>{
      //   item.attr_vals=item.attr_vals.length!==0?item.attr_vals.split(' '):[]
      // })
    },
    // 当复选框选定的状态发生变化时
    checkchange(a) {
      console.log(a);
    },
    // 处理图片预览
    handlePreview(file) {
      console.log(file);
      // 保存预览图片的路径
      this.lookUrl = file.response.data.url;
      this.dialogVisible = true;
    },
    // 处理移出图片的操作
    handleRemove(file) {
      // console.log(file);
      // 要删除图片的路径
      const deleteUrl = file.response.data.tmp_path;
      // 查询要删除的路径在数组中的索引
      const index = this.addGoodsForm.pics.findIndex(
        (i) => i.pic === deleteUrl
      );
      // 删除该项
      this.addGoodsForm.pics.splice(index, 1);
      // console.log(this.addGoodsForm);
    },
    // 监听图片上传成功的函数
    uploadSuccess(response) {
      // console.log(response);
      const url = { pic: response.data.tmp_path };
      this.addGoodsForm.pics.push(url);
      console.log(this.addGoodsForm.pics);
    },
    // 点击添加商品按钮
    addGoods() {
      // console.log(this.addGoodsForm);
      this.$refs.addGoodsFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error("请填写必要的表单项");
        }
        const form = _.cloneDeep(this.addGoodsForm);
        form.goods_cat = form.goods_cat.join(",");
        this.goodsManyParams.forEach((item) => {
          const many = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" "),
          };
          form.attrs.push(many);
        });
        this.goodsOnlyParams.forEach((item) => {
          const only = { attr_id: item.attr_id, attr_value: item.attr_vals };
          form.attrs.push(only);
        });

        // console.log(this.goodsManyParams);
        // console.log(this.goodsOnlyParams);
        // console.log(form);
        const {data:res}=await this.$http.post('goods',form)
        // console.log(res);
        if(res.meta.status!==201){
          return this.$message.error('添加商品失败')
        }
        this.$message.success('添加商品成功')
        this.$router.push('/goods')
      });
    },
  },
  created() {
    this.getGoodsList();
  },
};
</script>

<style scope>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.image {
  width: 450px;
}
.ql-editor {
  min-height: 300px;
}
.btnAdd {
  margin-top: 15px !important;
}
</style>